<!--
 * @Date: 2022-06-02 15:05:53
 * @Author: 陶子
 * @LastEditTime: 2022-08-12 13:56:54
 * @FilePath: \jk_one-stop_pc\src\components\pubBtn\PubExport.vue
 * @pageName: 这是--(公共导出组件)--页面
-->
<template>
  <div>
    <a-button @click="handleExport(selectedRows)" :type="btnType" style="float: right" :icon="icon">导出</a-button>
    <a-modal style="width: 50%" v-model="selectExportVisiable" title="导出">
      <template slot="footer">
        <a-button key="back" @click="handleExportAll" v-if="showAll"> 导出全部数据 </a-button>
        <a-button key="submit" type="primary" @click="handleSelectExport"> 导出选中数据 </a-button>
      </template>
      {{ selectExportTitle }}
    </a-modal>
  </div>
</template>
<script>
import moment from 'moment'
import { httpAction, getAction, deleteAction, downFile, downFilePost } from '@/api/manage'
export default {
  components: {},
  //propForm：要传的参数,需要处理好，再传入，若没有则不传；
  //sortForm：排序表单，若没有则不传；
  //action：请求方式，downFile：get请求，downFilePost：post请求，默认downFilePost；
  //tabName：子tab名，若没有则不传；
  //fullName：文件名全称，如果存在tabName或tableName则无效；
  //selectedRows：选择的数据——必传；
  //columns：展示的列——必传；
  //tableName：表名——必传；
  //exportUrl：导出接口地址——必传
  props: {
    icon: {
      type: String,
      default: 'upload'
    },
    propForm: {
      type: Object,
      default: () => {
        return {}
      },
    },
    sortForm: {
      type: Object,
      default: () => {
        return {}
      },
    },
    action: {
      type: String,
      default: 'downFilePost',
    },
    tabName: {
      type: String,
      default: '',
    },
    fullName: {
      type: String,
      default: '',
    },
    selectedRows: {
      type: Array,
      required: true,
    },
    columns: {
      type: Array,
      required: true,
    },
    showAll: {
      type: Boolean,
      default: true
    },
    tableName: {
      type: String,
      default: '',
    },
    exportUrl: {
      type: String,
      required: true,
    },
    btnType: {
      type: String,
      default: 'primary'
    }
  },
  data() {
    return {
      selectExportVisiable: false, // 导出弹窗
      selectExportParam: {}, // 导出参数
      filedKeys: '', // 导出字段
      fileName: '', // 导出文件名
      selectExportTitle: '',
    }
  },
  created() { },
  methods: {
    // 导出
    handleExport(e) {
      let that = this
      // 获取动态列
      let filedKeysList = []
      that.columns.forEach((item) => {
        //导出表格展示动态字段
        let keys = item.dataIndex ? item.dataIndex.split('.') : []
        if (keys.length == 2) {
          filedKeysList.push(keys[1])
        } else {
          filedKeysList.push(item.dataIndex)
        }
      })
      // filedKeysList.pop()//删除最后一个的操作列
      that.filedKeys = filedKeysList.join(',')
      //设置文件名
      if (that.tableName || that.tabName) {
        that.fileName = `${moment(new Date()).format('YYYY-MM-DD')}${that.tableName}${that.tabName ? '_' : ''}${that.tabName ? that.tabName : ''
          }`
      } else {
        that.fileName = that.fullName
      }
      if (!e || e.length === 0) {
        that.handleExportAll()
        that.selectExportVisiable = false
      } else {
        that.selectExportTitle = `已选中${e.length}条数据`
        that.selectExportVisiable = true
        that.selectExportParam = {
          ...that.propForm,
          ...that.sortForm,
          selectedList: e,
          fileName: that.fileName, //文件名
          filedKeys: that.filedKeys, //动态列
        }

        // 删除that.selectExportParam中的空子段
        for (let key in that.selectExportParam) {
          if (
            that.selectExportParam[key] == '' ||
            that.selectExportParam[key] == null ||
            that.selectExportParam[key] == []
          ) {
            delete that.selectExportParam[key]
          }
        }
      }
    },
    handleSelectExport() {
      this.selectExportVisiable = false
      let api = downFilePost
      if (this.action == 'downFile') {
        api = downFile
      }
      api(this.exportUrl, this.selectExportParam).then((data) => {
        if (data.type == 'application/json') {
          const reader = new FileReader() //创建一个FileReader实例
          reader.readAsText(data, 'utf-8') //读取文件,结果用字符串形式表示
          reader.onload = function () {
            //读取完成后,**获取reader.result**
            const msg = JSON.parse(reader.result)
            this.$antdMessage.error(msg.message) //弹出错误提示
          }
          return
        }
        if (!data) {
          this.$antdMessage.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), this.fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', this.fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    handleExportAll() {
      let that = this
      that.selectExportVisiable = false
      that.$antdConfirm({
        title: `导出`,
        content: `确定导出全部数据?`,
        onOk() {
          let param = {
            ...that.propForm,
            ...that.sortForm,
            fileName: that.fileName,
            filedKeys: that.filedKeys,
          }
          // 删除param中的空子段
          for (let key in param) {
            if (param[key] == '' || param[key] == null || param[key] == undefined || param[key] == []) {
              delete param[key]
            }
          }
          console.log(param, '导出选中数据param')
          let api = downFilePost
          if (that.action == 'downFile') {
            api = downFile
          }
          api(that.exportUrl, param).then((data) => {
            if (data.type == 'application/json') {
              const reader = new FileReader() //创建一个FileReader实例
              reader.readAsText(data, 'utf-8') //读取文件,结果用字符串形式表示
              reader.onload = function () {
                //读取完成后,**获取reader.result**
                const msg = JSON.parse(reader.result)
                that.$antdMessage.error(msg.message) //弹出错误提示
              }
              return
            }
            if (!data) {
              that.$antdMessage.warning('文件下载失败')
              that.selectExportVisiable = false
              return
            }
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
              window.navigator.msSaveBlob(new Blob([data]), that.fileName + '.xls')
              that.selectExportVisiable = false
            } else {
              let url = window.URL.createObjectURL(new Blob([data]))
              let link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              link.setAttribute('download', that.fileName + '.xls')
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link) //下载完成移除元素
              window.URL.revokeObjectURL(url) //释放掉blob对象
              that.selectExportVisiable = false
            }
          })
        },
        onCancel() { },
      })
    },
  },
}
</script>

<style scoped lang="less"></style>
